# -*- coding: utf-8 -*-
from PyQt4.QtGui import *
from PyQt4.QtCore import *
import sys
from PyQt4.QtNetwork import *

QTextCodec.setCodecForTr(QTextCodec.codecForName("utf8"))

class TcpClientSocket(QTcpSocket):
    def __init__(self,parent=None):
        super(TcpClientSocket,self).__init__(parent)
        self.connect(self,SIGNAL("readyRead()"),self.dataReceive)
        self.connect(self,SIGNAL("disconnected()"),self.slotDisconnected)
        self.length = 0
        self.msglist = QByteArray()
    
    def dataReceive(self):
        while self.bytesAvailable() > 0:
            length = self.bytesAvailable()
            msg = self.read(length)
            self.emit(SIGNAL("updateClients(QString, int, int)"),msg,length,self.socketDescriptor())
                    
    def slotDisconnected(self):
        self.emit(SIGNAL("disconnected"),self.socketDescriptor())
        

class Server(QTcpServer):
    def __init__(self,parent=None,port=0):
        super(Server,self).__init__(parent)
        self.count = 0
        self.client = []
        self.listen(QHostAddress.Any,port)
        
        self.tcpClientSocketList = []
    
    def incomingConnection(self,socketDescriptor):
        tcpClientSocket = TcpClientSocket(self)
        print "first client connected"
        
        self.connect(tcpClientSocket,SIGNAL("updateClients(QString, int, int)"),self.updateClients)
        self.connect(tcpClientSocket,SIGNAL("disconnected"),self.slotDisconnected)
        
        tcpClientSocket.setSocketDescriptor(socketDescriptor)
        self.tcpClientSocketList.append(tcpClientSocket)
        print self.tcpClientSocketList
    def updateClients(self,msg,length,descriptor):
        print msg
        print length
        print descriptor
        print msg.split(":")[0]
        if msg.split(":")[0] != "":
            self.emit(SIGNAL("updateServer(QString,int)"),msg,length)
            for i in xrange(len(self.tcpClientSocketList)):
                item = self.tcpClientSocketList[i]
                if item.socketDescriptor() != descriptor:
                    length_msg = item.writeData(msg)
                    if length_msg != msg.length():
                        continue
        else:
            self.emit(SIGNAL("updateServer(QString,int)"),msg,length)
            self.count+=1
            print "else"
            print self.count
            if  self.count < 3:
                for i in xrange(len(self.tcpClientSocketList)):
                    item = self.tcpClientSocketList[i]
                    if  item.socketDescriptor() == descriptor:
                        self.client.append(item)
                    if  item.socketDescriptor() != descriptor:
                        length_msg = item.writeData(msg)
                        if length_msg != msg.length():
                            continue
            else:
                print "Full!"
    
    def slotDisconnected(self,descriptor):
        print "descriptor"
        for i in xrange(len(self.tcpClientSocketList)):
            item = self.tcpClientSocketList[i]
            print item.socketDescriptor
            if item.socketDescriptor() == descriptor:
                self.tcpClientSocketList.remove(self.tcpClientSocketList[i])
                print self.tcpClientSocketList
                return
        return

class TcpServer(QDialog):
    def __init__(self,parent=None,f=None):
        super(TcpServer,self).__init__(parent)
        self.setWindowTitle("TCP Server")
        vbMain = QVBoxLayout(self)
        self.ListWidgetContent = QListWidget(self)
        vbMain.addWidget(self.ListWidgetContent)
        
        hb = QHBoxLayout()
        LabelPort = QLabel(self)
        LabelPort.setText(self.tr("Port:"))
        hb.addWidget(LabelPort)
        
        LineEditPort = QLineEdit(self)
        hb.addWidget(LineEditPort)
        
        vbMain.addLayout(hb)
        
        self.PushButtonCreate = QPushButton(self)
        self.PushButtonCreate.setText(self.tr("Create"))
        vbMain.addWidget(self.PushButtonCreate)
        
        self.connect(self.PushButtonCreate,SIGNAL("clicked()"),self.slotCreateServer)
        self.port  = 8090
        LineEditPort.setText(QString.number(self.port))
    
    def slotCreateServer(self):
        server = Server(self,self.port)
        print "server start"
        self.connect(server,SIGNAL("updateServer(QString,int)"),self.updateServer)
        self.PushButtonCreate.setEnabled(False)
    
    def updateServer(self,msg,length):
        self.ListWidgetContent.addItem(msg)
    
        
app=QApplication(sys.argv)
dialog=TcpServer()
dialog.show()
app.exec_()
